package org.qydjk.console.controller.sys;

import org.qydjk.common.controller.BaseController;
import org.qydjk.common.pojo.SResource;
import org.qydjk.common.shiro.vo.ShiroUser;
import org.qydjk.common.util.BeanUtil;
import org.qydjk.common.util.ListUtil;
import org.qydjk.common.util.StringUtil;
import org.qydjk.common.vo.Tree;
import org.qydjk.console.constant.ConsoleConstant;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;


@Controller
@RequestMapping("/resource")
public class SResourceController extends BaseController {
    private static final int RESOURCE_MENU = 0; // 菜单
    /**
     * 主页左侧树
     * @return
     */
    @RequestMapping("/tree.do")
    @ResponseBody
    public Object resourceTree(){
        try {
            ShiroUser shiroUser = getShiroUser();
            List<Tree> trees = new ArrayList<Tree>();
            // shiro中缓存的用户角色
            Set<String> roles = shiroUser.getRoles();
            if (ListUtil.isNullOrEmpty(roles)) {
                return trees;
            }
            // 如果有超级管理员权限
            if (roles.contains(ConsoleConstant.ADMINISTRATOR_ROLE_NAME)) {
                List<SResource> resourceLists = baseService.findByHql("from SResource s where s.resourceType = ? order by s.seq",RESOURCE_MENU);
                if (resourceLists == null) {
                    return trees;
                }
                return buildTree(resourceLists);
            }
            // 普通用户
            List<Integer> roleIdList = baseService.findByHql("select su.roleId from SUserRole su where su.userId = ?",shiroUser.getId());
            if (ListUtil.isNullOrEmpty(roleIdList)) {
                return trees;
            }
            StringBuffer sql = new StringBuffer("");
            sql.append("SELECT DISTINCT s.id, s.name, s.url,");
            sql.append(" s.description, s.icon,");
            sql.append(" s.pid, s.seq, s.status, s.open_mode,");
            sql.append(" s.opened, s.resource_type,s.create_time");
            sql.append(" FROM s_role r");
            sql.append(" LEFT JOIN s_role_resource e ON r.id = e.role_id");
            sql.append(" LEFT JOIN s_resource s ON e.resource_id = s.id");
            sql.append(" WHERE r.id in ("+StringUtil.intListToInSQL(roleIdList)+") AND s.resource_type = 0 ORDER BY s.seq");
            List<SResource> resourceLists = baseService.findBeanBySQL(sql.toString(),SResource.class);
            if (ListUtil.isNullOrEmpty(resourceLists)) {
                return trees;
            }
            return buildTree(resourceLists);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 构建树
     * @param resourceLists
     * @return
     */
    private List<Tree> buildTree(List<SResource> resourceLists){
        List<Tree> trees = new ArrayList<Tree>();
        for (SResource resource : resourceLists) {
            Tree tree = new Tree();
            tree.setId(resource.getId());
            tree.setPid(resource.getPid());
            tree.setText(resource.getName());
            tree.setIconCls(resource.getIcon());
            tree.setAttributes(resource.getUrl());
            tree.setOpenMode(resource.getOpenMode());
            //叶子节点state设置为closed，会无线循环他本身的数据结构
            //tree.setState(resource.getOpened());
            trees.add(tree);
        }
        return trees;
    }

    /**
     * “资源管理”入口
     * @return
     */
    @RequestMapping("/manager.do")
    public String resourceManager(){
        return "admin/resource/resource";
    }

    /**
     * 资源管理列表
     *
     * @return
     */
    @RequestMapping("/treeGrid.do")
    @ResponseBody
    public Object treeGrid() throws Exception {
        List<SResource> res = baseService.findByHql("from SResource sr order by sr.seq");
        return res;
    }

    /**
     * 添加资源页
     *
     * @return
     */
    @GetMapping("/addPage.do")
    public String addPage() {
        return "admin/resource/resourceAdd";
    }

    /**
     * 添加资源
     *
     * @param resource
     * @return
     */
    @RequestMapping("/add.do")
    @ResponseBody
    public Object add(@Valid SResource resource) throws Exception {
        resource.setCreateTime(new Date());
        // 选择菜单时将openMode设置为null
        Integer type = resource.getResourceType();
        if (null != type && type == 0) {
            resource.setOpenMode(null);
        }
        baseService.save(resource);
        return renderSuccess("添加成功！");
    }

    /**
     * 查询所有的菜单
     */
    @RequestMapping("/allTree.do")
    @ResponseBody
    public Object allMenu() throws Exception {
        List<Tree> trees = new ArrayList<Tree>();
        // 查询所有菜单
        List<SResource> resourceLists = baseService.findByHql("from SResource s where s.resourceType = ? order by s.seq",RESOURCE_MENU);
        if (resourceLists == null) {
            return trees;
        }
        return buildTree(resourceLists);
    }

    /**
     * 查询所有的资源tree
     */
    @RequestMapping("/allTrees.do")
    @ResponseBody
    public Object allTree() throws Exception {
        // 获取所有的资源 tree形式，展示
        List<Tree> trees = new ArrayList<Tree>();
        List<SResource> resourceLists = baseService.findByHql("from SResource sr order by sr.seq");
        if (resourceLists == null) {
            return trees;
        }
        return buildTree(resourceLists);
    }

    /**
     * 编辑资源页
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping("/editPage.do")
    public String editPage(Model model, Integer id) throws Exception {
        SResource resource = baseService.get(SResource.class,id);
        model.addAttribute("resource", resource);
        return "admin/resource/resourceEdit";
    }

    /**
     * 编辑资源
     *
     * @param resource
     * @return
     */
    @RequestMapping("/edit.do")
    @ResponseBody
    public Object edit(@Valid SResource resource) throws Exception {
        SResource ss = baseService.get(SResource.class, resource.getId());
        BeanUtil.copyProperties(resource,ss);
        baseService.update(ss);
        return renderSuccess("编辑成功！");
    }

    /**
     * 删除资源
     *
     * @param id
     * @return
     */
    @RequestMapping("/delete.do")
    @ResponseBody
    public Object delete(Integer id) throws Exception {
        //子节点必须为空
        int ct = baseService.getRecordCountHQL("select count(r.id) from SResource r where r.pid = ?",id.intValue());
        if(ct > 0){
            return renderError("请先将子节点删除");
        }
        SResource resource = new SResource();
        resource.setId(id);
        baseService.delete(resource);
        return renderSuccess("删除成功！");
    }
}
